package com.feng.controller;

import com.feng.entity.ResponseResult;
import com.feng.enums.ErrorEnum;
import com.feng.enums.FileEnum;
import com.feng.exception.BusinessException;
import com.feng.service.FileService;
import com.feng.util.ResponseResultUtil;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;


@RestController
@RequestMapping("/files")
@Slf4j
@Api(tags = "文件上传接口")
public class FileUploadController {
    @Autowired
    private FileService fileService;
    @Value("${file.uploadPath}")
    private String fileSaveBasePath ;

    @PostMapping("/upload")
    @ResponseBody
    public ResponseResult upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        String fileExt[] = {"doc", "docx"};    //检查文件是否是doc或者docx
        checkFileExt(file, fileExt, "请上传doc,docx格式文件"); //验证是否是上一行所描述的文件，如果不是，则提示
        String relativePath = "/files/";   //定义文件保存的相对路径（这里设置为“/files/”），获取上传文件的原始名称，并根据当前时间戳生成唯一的文件保存路径
        String fileName = file.getOriginalFilename();    //用于存储从文件上传表单中接收到的原始文件名。
        String fileSavePath = getFileSavePath(relativePath);   //用于获取存储上传文件的服务器上的实际路径
        relativePath = relativePath + fileName;   //将相对路径和文件名拼接成完整的文件保存路径，并创建一个file对象来代表该文件。
        File dest = new File(fileSavePath + fileName);//创建了1个名为dest的file对象，该对象表示希望在本地磁盘上保存的文件路径以及文件名，relativePath + filename表示文件在服务器上的存储位置
        try {
            file.transferTo(dest);  //此方法把上传到file的文件转移到dest目录下
            com.feng.entity.File fileObj = new com.feng.entity.File(fileName, relativePath, FileEnum.CLUB_FILE.getFileId());//接着创建一个名为fileobj的文件实体对象，并传入文件名、相对路径和业务类型参数等属性
            fileService.insert(fileObj);  //通过此方法将对象插入到数据库中，以便之后可以根据业务需求进行查询、修改或删除操作。
            log.info("上传成功");
            return ResponseResultUtil.renderSuccess(fileObj);
        } catch (IOException e) {
            log.error(e.toString(),e);   //log 是一个用于记录日志信息的对象，.error() 表示记录错误级别的日志。括号中的 e.tostring() 表示将异常对象 e 转化为字符串，用于在日志中打印错误信息，而逗号后面的 e 则表示将异常对象本身作为参数传递给 error() 方法。
        }
        return ResponseResultUtil.renderError(ErrorEnum.FILE_UPLOAD_FAIL);
    }

    @PostMapping("/uploadImg")
    @ResponseBody
    public ResponseResult uploadImg(@RequestParam("file") MultipartFile file,String relativePath, HttpServletRequest request) throws IOException {
        String fileExt[] = {"jpg", "png"};
        checkFileExt(file, fileExt, "请上传jpg,png格式图片");
//        String relativePath = "/images/";
        if(StringUtils.isEmpty(relativePath)){
            relativePath = "/images/";
        }
        String fileName = file.getOriginalFilename();
        String absolutePath = getFileSavePath(relativePath)+"/"+ fileName;
       String imgRelativePath = relativePath +"/"+ fileName;
        System.out.println(imgRelativePath);
        File dest = new File(absolutePath);
        try {
            file.transferTo(dest);
//            fileService.insert(new com.feng.entity.File(fileName, relativePath, FileEnum.COMMON_IMG.getFileId()));
            log.info("上传成功");
            return ResponseResultUtil.renderSuccess(imgRelativePath);
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        return ResponseResultUtil.renderError(ErrorEnum.FILE_UPLOAD_FAIL);
    }
    @PostMapping("/uploadCarouselImg")
    @ResponseBody
    public ResponseResult uploadIndexCarouselImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
        String fileExt[] = {"jpg", "png"};
        checkFileExt(file, fileExt, "请上传jpg,png格式图片");
        String relativePath = "/carousel-img/";
        String fileName = file.getOriginalFilename();
        String imgSavePath = getFileSavePath(relativePath);
        relativePath = relativePath + fileName;
        File dest = new File(imgSavePath + fileName);
        try {
            file.transferTo(dest);
            fileService.insert(new com.feng.entity.File(fileName, relativePath, FileEnum.CAROUSEL_IMG.getFileId()));
            log.info("上传成功");
            return ResponseResultUtil.renderSuccess(relativePath);
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        return ResponseResultUtil.renderError(ErrorEnum.FILE_UPLOAD_FAIL);
    }
    private void checkFileExt(MultipartFile file, String fileExt[], String msg) {
        boolean checkResultError = true;
        if (file.isEmpty()) {
            throw new BusinessException(ErrorEnum.FILE_NULL);
        }

        String fileName = file.getOriginalFilename();
        String uploadFileExt = fileName.substring(fileName.indexOf('.') + 1);
        if (fileExt == null || fileExt.length == 0) {
            checkResultError = false;
        } else {
            for (String s : fileExt) {
                if (uploadFileExt.equals(s)) {
                    checkResultError = false;
                    break;
                }
            }
        }


        if (checkResultError) {
            throw new BusinessException(ErrorEnum.FILE_FORMAT_ERROR.setMsg(msg));
        }
    }


    private String getFileSavePath(String relativePath) {
        String filePath = fileSaveBasePath + relativePath;
        System.out.println(filePath);
        File fileSave = new File(filePath);
        if (!fileSave.exists()) {
            fileSave.mkdirs();
        }
        return filePath;
    }
}
